<template>
  <el-dialog
    title="读卡"
    class="gl_dialog_TitleLine gl_dl_footer"
    :visible.sync="dialogVisible"
    :close-on-click-modal="false"
    :before-close="cancelDialog"
    width="750px"
  >
    <div class="outer">
      <div v-if="bindStatus === 'noCard'" class="no_card">请将会员卡置于读卡器处</div>
      <div v-if="bindStatus === 'knownCard'" class="no_card outer_padding">
        <div class="item"><span class="label">会员卡</span><span>{{ knownInfo.cardNumber }}</span></div>
        <div class="item"><span class="label">学生姓名</span><span>{{ knownInfo.name }}</span></div>
      </div>
      <div v-if="bindStatus === 'unknownCard'" class="no_card">暂无绑定信息</div>
      <div v-if="bindStatus === 'cardError'" class="no_card errorMsg">{{ errorMsg }}</div>
    </div>
  </el-dialog>
</template>

<script>
import {
  api_GET_ClubClubSecretKey, // 获取密钥
  api_GET_ClubClubCardStudent // 依据卡号查人/依据卡查人
} from '@/extend/api/hall.js';
import axios from 'axios';
export default {
  data () {
    return {
      secretKey: '',
      bindStatus: 'noCard',
      dialogVisible: false,
      errorMsg: '',
      knownInfo: {
        name: '',
        cardNumber: ''
      },
      physicalCardId: '',
      cardSN: ''
    };
  },
  watch: {
    'physicalCardId': {
      immediate: true,
      deep: true,
      handler(val, old) {
        if (val) {
          this.getKnownCardInfo(val);
        }
      }
    }
  },
  methods: {
    /**
      1.获取密钥,生成卡号
      2.循环读卡 -读到卡时判断卡片状态
        b.非白卡，有绑定信息---解绑
        c.非白卡，无绑定信息---绑定
        c.未识别卡片---报错3s后重读
    */
    init() {
      this.getSecretKey().then((res) => {
        this.secretKey = res.secretKey;
        this.readCardsn();
      });
    },
    // 1.获取密钥
    getSecretKey() {
      return new Promise((resolve, reject) => {
        api_GET_ClubClubSecretKey().then(res => {
          resolve(res);
        }, error => {
          this.$message({ type: 'error', message: '获取道馆密钥失败！' });
          reject(error);
        });
      });
    },
    // 1.读卡号-------判断读卡器上是否有卡
    readCardsn() {
      if (!this.dialogVisible) {
        return false;
      }
      const that = this;
      axios
        .post('http://localhost:36881/M1/Getsnr', {
          mode: 38,
          halt: 0
        })
        .then((res) => {
          if (res && res.data && res.data.Status === 1) {
            that.bindStatus = 'noCard';
            that.cardSN = '';
            that.physicalCardId = '';
            setTimeout(() => {
              that.readCardsn();
            }, 1000);
          } else if (res && res.data && res.data.Status === 0) {
            if (that.cardSN === res.data.card_sn) {
              setTimeout(() => {
                that.readCardsn();
              }, 1000);
            } else {
              that.controlBuzzer().then(() => {
                that.cardSN = res.data.card_sn;
                that.readCardData();
              });
            }
          } else {
            that.getError(res);
          }
        }, error => {
          const _msg = error.message === 'Network Error' ? '网络错误，请安装读卡服务后重试！' : error.message;
          that.$message({ type: 'error', message: _msg });
        });
    },
    // 2.读卡数据--并根据读卡结果做相应操作
    readCardData(password) {
      const that = this;
      password = password || 'FFFFFFFFFFFF';
      axios
        .post('http://localhost:36881/M1/Read', {
          inf_mode: 0,
          blk_add: 4,
          num_blk: 1,
          card_password: password
        })
        .then((res) => {
          if (res && res.data && res.data.Status === 1) {
            if (password === 'FFFFFFFFFFFF') {
              // 使用默认密码读取失败---------卡密重读
              that.readCardData(that.secretKey);
            } else {
              // 使用卡密读取失败---------重读
              that.bindStatus = 'cardError';
              that.errorMsg = '无法识别卡片，请重试';
              setTimeout(() => {
                that.bindStatus = 'noCard';
                that.errorMsg = '';
                that.readCardsn();
              }, 3000);
            }
          } else if (res && res.data && res.data.Status === 0) {
            if (password === 'FFFFFFFFFFFF') {
              // 使用默认密码读取成功------白卡
              this.bindStatus = 'unknownCard';
              that.physicalCardId = '';
              setTimeout(() => {
                that.readCardsn();
              }, 3000);
            } else {
              // 使用卡密读取成功------获取卡片信息对应学生信息
              that.physicalCardId = res.data.data;
            }
          } else {
            that.getError(res);
          }
        }, error => {
          const _msg = error.message === 'Network Error' ? '网络错误，请在实体卡管理页面下载并安装读卡服务后重试！' : error.message;
          that.$message({ type: 'error', message: _msg });
        });
    },
    // 依据卡号查人/依据卡查人
    getKnownCardInfo(data) {
      const that = this;
      const qo = {
        ClubCardNumber: data,
        IncludeClubCard: true,
        IncludeRegisterStudernt: true
      };
      api_GET_ClubClubCardStudent(qo).then(res => {
        if (res.items && res.items.length > 0) {
          // 查询到卡片绑定信息
          this.bindStatus = 'knownCard';
          this.knownInfo.name = res.items[0].registerStudent && res.items[0].registerStudent.name;
          this.knownInfo.cardNumber = res.items[0].clubCard && res.items[0].clubCard.cardNumber;
        } else {
          this.bindStatus = 'unknownCard';
        }
        setTimeout(() => {
          that.readCardsn();
        }, 3000);
      }, error => {
        // 读取卡片对应信息失败
        this.bindStatus = 'cardError';
        this.errorMsg = error.error.message || error.message;
        setTimeout(() => {
          that.readCardsn();
        }, 3000);
      });
    },
    controlBuzzer() {
      const that = this;
      return new Promise((resolve, reject) => {
        axios
          .post('http://localhost:36881/M1/ControlBuzzer', {
            freq: 18,
            duration: 1
          })
          .then((res) => {
            if (res && res.data && res.data.Status === 0) {
              console.log('-------蜂鸣器');
            } else if (res && res.data && res.data.Status === 1) {
              that.$message({ type: 'error', message: res.data.Msg });
            } else {
              that.getError(res);
            }
            resolve(res);
          }, error => {
            reject(error);
            const _msg = error.message === 'Network Error' ? '网络错误，请安装读卡服务后重试！' : error.message;
            that.$message({ type: 'error', message: _msg });
          });
      });
    },
    getError(res) {
      const that = this;
      if (res && res.data && res.data.Status === 800018) {
        that.$message({ type: 'error', message: '读卡设备不存在，请连接后重试！' });
      } else if (res && res.data && res.data.Status === 90001) {
        that.$message({ type: 'error', message: '缺少必要参数，请重试！' });
      } else {
        that.$message({ type: 'error', message: res.data && res.data.Msg });
      }
    },
    cancelDialog() {
      this.dialogVisible = false;
      this.bindStatus = 'noCard';
      this.errorMsg = '';
      this.cardSN = '';
      this.knownInfo = { name: '', cardNumber: '' };
    }
  }
};
</script>

<style lang="scss" scoped>
.outer {
   height: 450px;
}
.outer_padding {
  padding: 70px 80px 30px 100px;
}
.no_card {
  height: 100%;
  line-height: 410px;
  font-size: 32px;
  font-weight: bold;
  text-align: center;
  color: #333;
}
.errorMsg {
  color: #ff0000;
}
.fs_24 {
  font-size: 24px;
}
.item {
  padding: 25px 0px;
  font-size: 18px;
  line-height: normal;
  text-align: left;
  span {
    display: inline-block;
    font-weight: normal;
  }
  .label {
    width: 150px;
    font-size: 24px;
    font-weight: bold;
  }
}
</style>

